<?php

namespace app\admin\controller;

use think\Db;
use think\Request;
use think\Exception;//事务处理

class Proattr extends Auth
{
    public function __construct(Request $request){
        $this->getChildIDdata = [];
        parent::__construct($request);
        $this->data = $request->param();
        $this->lang = isset($this->data['lang']) && $this->data['lang'] ? $this->data['lang'] : is_lang();
        $this->user_id = session('userid') == null ? 1 : session('userid');
    }

    //分类编辑

    // 产品属性list
    public function list(Request $request)
    {   
        // 查找
        if(isset($this->data['searchText']) && $this->data['searchText']){  
        
            $join = [
                ['proattr at', 'mu.mkey = at.mkey']
            ];
            $searchTextWhere['mu.content'] = ['like', '%' . $this->data['searchText'] . '%'];
            $searchTextWhere['mu.lang'] = $this->lang;

            $attrdata = getSearch('multi_lang','mu',['at.*,mu.content'],$searchTextWhere,$join,'mu.id asc');
            
            $searchText = $this->data['searchText'];
        }else{
            $join = [
                        ['multi_lang mu','zu.mkey = mu.mkey']
                    ];
            $where['lang'] = $this->lang;
            // $where['product_attr_status'] = ['in',('1,3,4')]; 
            $attrdata = getSearch('proattr','zu',['zu.*,mu.content'],$where,$join,'zu.drank asc');
        
            $searchText = '';
        }
        // dump($attrdata);die;
        // 获取属性类型
        foreach ($attrdata as $k => $v) {
            $where1['zu.proattr_id'] = $v['id'];
            $where1['mu.lang'] = $this->lang;
            $child = getSearch('proattr_value','zu',['mu.content'],$where1,[['multi_lang mu','zu.mkey = mu.mkey']],'zu.id asc');
            // return $child;
            $attrdata[$k]['childname'] = '';
            foreach ($child as $k1 => $v1) {
                $attrdata[$k]['childname'] .= $v1['content'].',';
            }
            $attrdata[$k]['childname'] = rtrim($attrdata[$k]['childname'],',');
            $attrdata[$k]['cateCount'] = 1;
        }


        $returnData['size'] = count( $attrdata);

        // 获取分页数据
        if(isset($this->data['page']) && isset($this->data['limit'])){
            if($this->data['limit']*($this->data['page']-1) < $returnData['size']){
                $attrdata = array_slice($attrdata,$this->data['limit']*($this->data['page']-1),$this->data['limit']);
                $returnData['page'] = $this->data['page'];
            }
        }else{
            $returnData['page'] =1;
        }
        


        $id_array = [];
        // 拆分遍历获取所属分类信息
        if(!empty($attrdata)){
            foreach ($attrdata as $k => $v) {
                $attrdata[$k]['is_public'] = $v['is_public'] == 1 ? "P" : '-' ;
                $attrdata[$k]['status_name'] = $v['status'] == 1 ? lang('normal') : lang(getViewMultiLanguage($v['status']));
                $attrdata[$k]['isdel'] = $v['status'] == 2 ? "D" : '-';
                if($v['procat_ids'] != 0){
                    $product_cate_array = explode(',', $v['procat_ids']);
                    $product_cate = '';
                    foreach ($product_cate_array as $k1 => $v1) {
                        $catename = Db::name('multi_lang')->field(['content catelangname'])->where('mkey',"procat_".$v1)->where('lang',$this->lang)->find();
                        $attrdata[$k]['product_cate_array'][] = $catename;
                        $product_cate .= $catename['catelangname'].',';
                        // $attrdata[$k]['product_cate_array'][] = "product_cate_".$v1;
                    }
                    $attrdata[$k]['product_cate'] = rtrim($product_cate,',');

                }else{
                    $product_cate_array = '';
                }

                $id_array[] = $v['id'];
            }
        }

        // 获取多语言种类
        $language_type = getLanguage();
        // dump($language_type);die;
        if($request->isAjax()){
            $returnData['attrdata'] = $attrdata;
            $returnData['searchText'] = $searchText;
            $returnData['id_array'] = $id_array;
            $returnData['language_type'] = $language_type;
            $returnData['titleStr'] = lang('product_properties');
            return json_encode($returnData);
        }else{
            return view('attrlist',['attrdata'=>$attrdata]);
        }
    }


    // 产品属性新增
    public function attrAdd()
    {
        if($this->data['request'] == 'add'){
            return view('attropen',['title'=>lang('add_product_properties'),'request'=>'add']);
        }else if($this->data['request'] == 'insert'){
            unset($this->data['request']);
            // return $this->data;
            if(isset($this->data['zh']['classname']) && $this->data['zh']['classname']['val'] != ''){
                if(isset($this->data['zh']['valarr']) && $this->data['zh']['valarr'][0]['val'] != ''){

                    $where['mkey'] = ['like','%proattr%'];
                    $where['content'] = $this->data['zh']['classname']['val'];
                    $where['lang'] = $this->lang;
                    if(hasData('multi_lang',$where)){
                        return json_encode(array('status'=>3,'msg'=>lang('product_properties').$this->data['zh']['classname']['val'].' '.lang('already_exists')));
                    }
                    $dataInsert['drank'] = (Db::name('proattr')->order('drank desc')->value('drank'))+1;
                    // 开启事务
                    Db::startTrans();
                    // try{
                        $attrId = insertData('proattr',$dataInsert);
                        if($attrId){
                            $i=0;
                            // foreach ($this->data as $k => $v) {

                                $lang_cate = getLanguage();
                                foreach ($lang_cate as $k => $v) {
                                    // 组装属性值数据 方便多语言新增
                                    foreach ($this->data['zh']['valarr'] as $k1 => $v1) {
                                        $data[$k1]['proattr_value'][$i]['lang']= $v['code'];
                                        $data[$k1]['proattr_value'][$i]['content']= $v1['val'];
                                    }
                                    // 组装属性名称数据
                                    $status = $this->data['zh']['state'];
                                    $proattr['lang'] = $v['code'];
                                    $proattr['content'] = $this->data['zh']['classname']['val'];
                                    $proattr['mkey'] = 'proattr_'.$attrId;
                                    $b = insertData('multi_lang',$proattr);
                                    $i++;
                                }
                            // }
                                // return $b;
                            $res = updateData('proattr',['id'=>$attrId],['mkey'=>'proattr_'.$attrId,'status'=>$this->data['zh']['state'],'is_public'=>$this->data['zh']['general']]);
                            // return $data;

                            if($res >= 0){
                                $res1 = $this->attrAddChild($data,$attrId);
                                if($res1['status'] == 1){
                                    //提交事务
                                    Db::commit();
                                }else{
                                    Db::rollback();
                                }
                                return json_encode($res1);
                            }
                        }
                        
                    // }catch (\Exception $e) {
                    //     //回滚事务
                    //     Db::rollback();
                    //     return  json_encode(array('code' => 500,'msg'=>lang('abnormal_error')));
                    // }
                }else{
                    return json_encode(array('status'=>2,'msg'=>lang('missing').' '.lang('attribute_value')));
                }
            }else{
                return json_encode(array('status'=>2,'msg'=>lang('missing_name')));
            }
        }else{
            return json_encode(array('status'=>2,'msg'=>lang('improve_submission_data')));
        }
        
    }

    function attrAddChild($data,$attrId)
    {
            if($attrId){
                // 开启事务
                Db::startTrans();   
                // try{
                    foreach ($data as $k => $v) {
                        // return $data;
                        $res = insertData('proattr_value',['proattr_id'=>$attrId]);
                        if($res){
                            $res1 = updateData('proattr_value',['id'=>$res],['mkey'=>'proattr_value_'.$res]);
                        }
                        foreach ($v as $k1 => $v1) {
                            // return $v1;
                            $noticValue = '';
                            foreach ($v1 as $k2 => $v2) {
                                $v2['mkey'] = 'proattr_value_'.$res;
                                $res2 = insertData('multi_lang',$v2);
                                    
                                if($k2<4){
                                    $noticValue .= $v2['content'];
                                }
                                if($k2 = 4){
                                    $noticValue .= '...';
                                }
                            }
                        }
                    }                    

                    if($res2 && $res){
                        //提交事务
                        Db::commit();
                        return array('status'=>1,'msg'=>lang('product_properties').'->'.getValue('multi_lang',['mkey'=>'proattr_'.$attrId,'lang'=>$this->lang],'content').'value:'.$noticValue.' '.lang('added_successfully'));
                    }else{
                        Db::rollback();
                        return array('status'=>0,'msg'=>lang('product_properties').'->'.getValue('multi_lang',['mkey'=>'proattr_'.$attrId,'lang'=>$this->lang],'content').'value:'.$noticValue.' '.lang('add_failed'));
                    }
                // }catch (\Exception $e) {
                //     //回滚事务
                //     Db::rollback();
                //     return  array('code' => 500,'msg'=>lang('product_properties').'->'.getValue('multi_lang',['mkey'=>'proattr_'.$attrId,'lang'=>$this->lang],'content').'value:'.$noticValue.lang('add_failed'));
                // }
            }else{
                return array('status'=>0,'msg'=>lang('product_properties').' '.lang('add_failed'));
            }
        
    }

    // 属性编辑
    public function attrEdit(){
        if($this->data['request'] == 'edit'){
            // 获取被编辑得数据
            $selfdata = getMultiLangName('proattr',['*'],['id'=>$this->data['id']],'id desc')[0];
            // return $selfdata;
            $value = getDatas('proattr_value',['*'],['proattr_id'=>$selfdata['id']],'id desc');
            // return $value;
            if(!empty($value)){
                foreach ($value as $k => $v) {
                    $valuename = getDatas('multi_lang',['*'],['mkey'=>$v['mkey']],'id desc');
                    foreach ($valuename as $k1 => $v1) {
                        $selfdata['valuename'][$v1['lang']][$k]['value'] = $v1['content'];
                        $selfdata['valuename'][$v1['lang']][$k]['mkey'] = $v1['mkey'];
                    }
                }
            }
            // dump($selfdata);die; 
            $language_type = getLanguage($this->lang);
            return view('attropen',['selfdata'=>$selfdata,'title'=>lang('edit_product_properties'),'request'=>'edit','language_type'=>$language_type]);

        }else if($this->data['request'] == 'update'){
            unset($this->data['request']);
            $res = $this->attrEditChild($this->data);
            // dump($res);die;
            return $res;
        }else{
            return json_encode(array('code' => 500,'msg'=>lang('improve_submission_data')));
        }
    }


    function attrEditChild($data)
    {
        // return $data;
        Db::startTrans();   
        // try{    
        foreach ($data as $k => $v) {
            if($v['classname']['val'] == ''){
                return json_encode(array('status'=>2,'msg'=>lang('improve_submission_data')));
            }else{
                // 编辑属性名称
                $res_attr = updateData('proattr',['id'=>$v['classname']['id']],['status'=>$v['state'],'is_public'=>$v['general']]);
                $res_attr_multi = updateData('multi_lang',['mkey'=>'proattr_'.$v['classname']['id'],'lang'=>$k],['content'=>$v['classname']['val']]);
                // 获取当前语言的返回名称
                if($k == $this->lang){
                    $content = $v['classname']['val'];
                }
                // 编辑的Id where条件
                $proattr_id = $v['classname']['id'];
                // 获取属性值
                $proattr_value[$k] = $v['valarr'];
                // 获取每种语言下的属性值数量
                $count = count($v['valarr']);
            }
        }
        // return $proattr_id;
        //因为又新增属性值数据，而且可能在view被删除的属性值没带过来，所以先把所以绑定的属性值删除再从新新增绑定
        $proattr_valueId = getDatas('proattr_value',['id'],['proattr_id'=>$proattr_id]);
        if(!empty($proattr_valueId)){
            $proattr_valueDel = deleteData('proattr_value',['proattr_id'=>$proattr_id]);
            if($proattr_valueDel){
                foreach ($proattr_valueId as $k1=> $v1) {
                    $proattr_valueMultiDel = deleteData('multi_lang',['mkey'=>'proattr_value_'.$v1['id']]);
                }
            }
        }
        // 整理属性值数据
        for ($i=0; $i < $count; $i++) { 
            foreach ($proattr_value as $k2 => $v2) {
                $proattr_valueFor[$i][$k2] = $v2[$i];
            }
        }
        $value = '';
        foreach ($proattr_valueFor as $k3 => $v3) {
            $insertValue = insertData('proattr_value',['proattr_id'=>$proattr_id]);
            if($insertValue){
                $res = updateData('proattr_value',['id'=>$insertValue],['mkey'=>'proattr_value_'.$insertValue]);
                if($res){
                    foreach ($v3 as $k4 => $v4) {
                        $proattr_insertValue['mkey'] = 'proattr_value_'.$insertValue;
                        $proattr_insertValue['content'] = $v4['val'];
                        $proattr_insertValue['lang'] = $k4;
                        $multiUpdate = insertData('multi_lang',$proattr_insertValue);
                        // 获取当前语言的返回值
                        if($k2 == $this->lang){
                            $value .= ','.$v4['val'];
                        }
                    }
                }
            }
        }
        ltrim($value,',');
        if($multiUpdate){
            Db::commit();
            return json_encode(array('status'=>1,'msg'=>lang('product_properties').'->'.$content.' '.lang('value').':'.$value.' '.lang('added_successfully')));
        }else{
            Db::rollback();
            return json_encode(array('status'=>0,'msg'=>lang('product_properties').'->'.$content.' '.lang('value').':'.$value.' '.lang('add_failed')));
        }
        // }catch (\Exception $e) {
        //     //回滚事务
        //     Db::rollback();
        //     return  json_encode(array('code' => 500,'msg'=>'mysql_fail'));
        // }
    }


    // 属性指定分类
    public function attrBindType()
    {
        if($this->data['request'] == 'list'){
            // 获取指定分类数据
            $selfdata = getMultiLangName('proattr',['*'],['id'=>$this->data['id']],'id desc')[0];
            $selfdata['status_name'] = getViewMultiLanguage($selfdata['status'],$this->lang);
            // dump($selfdata);die;
            // 整理已绑定分类数据
            if($selfdata['procat_ids'] == '' ){
                // $selfdata = '';
                $selfcate_array = [];
            }else{
                $selfcate_array = explode(',', $selfdata['procat_ids']);
                foreach ($selfcate_array as $k => $v) {
                    $catRes = getDatas('multi_lang',['*'],['mkey'=>'procat_'.$v]);
                    foreach ($catRes as $k1 => $v1) {
                        $selfdata['catename'][$v1['lang']][$k] = $v1['content'];
                    }
                }
            }
            // 获取所有正常状态分类
            $cateAll = getMultiLangName('procat',['*'],['status'=>1],'id desc');
            $cateAll = getTree($cateAll);
            // return $cateAll;die;
            return view('fiedopen',['selfdata'=>$selfdata,'cateAll'=>$cateAll,'selfcate_array'=>$selfcate_array]);

        }else if($this->data['request'] == 'bind'){
            if(!empty($this->data['id'])){
                if(!empty($this->data['procat_id'])){
                    $res = updateData('proattr',['id'=>$this->data['id']],['procat_ids'=>implode(',', $this->data['procat_id'])]);
                    if($res >= 0){
                        return json_encode(array('status'=>1,'msg'=>lang('product_properties').'->'.getValue('multi_lang',['mkey'=>'proattr_'.$this->data['id'],'lang'=>$this->lang],'content').lang('bind_success')));
                    }else{
                        return json_encode(array('status'=>0,'msg'=>lang('product_properties').'->'.getValue('multi_lang',['mkey'=>'proattr_'.$this->data['id'],'lang'=>$this->lang],'content').lang('bind_fail')));
                    }
                }else{
                    return json_encode(array('status' =>2,'msg'=>lang('improve_submission_data')));
                }
            }else{
                return json_encode(array('status' =>2 ,'msg'=>lang('improve_submission_data')));
            }
            
        }else{
            return json_encode(array('status' =>2,'msg'=>lang('improve_submission_data')));
        }
    }

    // 下架/批量下架，软删除/批量软删除，恢复/批量恢复，清除/批量清除
    public function changeStatus($data,$lang){
        // return $this->data;
        if(!empty($data['id'])){  // 判断条件是否达成
            if($data['fun'] == 'update'){
                $updateData = ['status'=>$data['value']];
                Db::startTrans();
                // try{
                    $content = '';
                    if(is_array($data['id'])){    // 是否批量删除
                        foreach ($data['id'] as $k => $v) {   
                            if($data['value'] == 2){
                                $public = getValue('proattr',['id'=>$v],'is_public');
                                if($public ==1){
                                    return json_encode(array('status'=>2,'msg'=>lang(getViewMultiLanguage($data['value'])).' '.lang('failed').' '.lang('attributes_common,_need_to_disarm_first')));
                                }
                            }
                            if($k < 3){
                                $content .= ','.getValue('multi_lang',['mkey'=>'proattr_'.$v],'content');
                            }
                            if($k = 3){
                                $content .= '...';
                            }
                            $res = updateData($data['table'],['id'=>$v],$updateData); 
                        }
                        ltrim($content,',');
                        if($res >= 0){
                            Db::commit();
                            return json_encode(array('status'=>1,'msg'=>lang('product_properties')."->".$content.'：'.lang(getViewMultiLanguage($data['value'])).' '.lang('successfully')));
                        }else{
                            return json_encode(array('status'=>0,'msg'=>lang('product_properties')."->".$content.'：'.lang(getViewMultiLanguage($data['value'])).' '.lang('failed')));
                        }
                    }else{

                        if($data['value'] == 2){
                            $public = getValue('proattr',['id'=>$data['id']],'is_public');
                            if($public ==1){
                                return json_encode(array('status'=>2,'msg'=>lang(getViewMultiLanguage($data['value'])).' '.lang('failed').' '.lang('attributes_common,_need_to_disarm_first')));
                            }
                        }
                        $content .= getValue('multi_lang',['mkey'=>'proattr_'.$data['id'],'content']);
                        $res = updateData($data['table'],['id'=>$data['id']],$updateData);
                        if($res){
                            Db::commit();
                            return json_encode(array('status'=>1,'msg'=>lang('product_properties')."->".$content.'：'.lang(getViewMultiLanguage($data['value'])).' '.lang('successfully')));
                        }else{
                            return json_encode(array('status'=>0,'msg'=>lang('product_properties')."->".$content.'：'.lang(getViewMultiLanguage($data['value'])).' '.lang('failed')));
                        }
                    }
                // }catch(\Exception $e){
                //     Db::rollback();
                //     return json_encode(array('status'=>500,'msg'=>$e));
                // }
            }else if($data['fun'] == 'deletes'){     // 清除
                Db::startTrans();
                // try{
                    $content = '';
                    if(is_array($data['id'])){    // 是否批量删除
                        foreach ($data['id'] as $k => $v) {  
                            $proattrRes = getDatas('proattr',['*'],['id'=>$v]);
                            if(!empty($proattrRes)){
                                if($proattrRes[0]['status'] !=2){
                                    return json_encode(array('status'=>2,'msg'=>lang("the_current_attribute_can't_be_cleared,_and_the_status_isn't_recycled")));
                                }

                                if($proattrRes[0]['is_public'] ==1){
                                    return json_encode(array('status'=>2,'msg'=>lang('clear_failed').' '.lang('attributes_common,_need_to_disarm_first')));
                                }
                            }
                            // 获取旗下所有属性值ID
                            $delIds = getDatas('proattr_value',['id'],['proattr_id'=>$v]);
                            // 删除旗下所有属性值
                            $res = deleteData('proattr',['id'=>$v]); 
                            // return $res;
                            if($res){
                                $res2 = deleteData('proattr_value',['proattr_id'=>$v]); 
                                foreach ($delIds as $k1 => $v1) {
                                    if($k1 < 4){
                                        $content .= ','.getValue('multi_lang',['mkey'=>'proattr_'.$v1['id'],'lang'=>$lang],'content');
                                    }
                                    if($k1 = 4){
                                        $content .= '';
                                    }
                                    $res1 = deleteData('multi_lang',['mkey'=>$data['table'].'_'.$v]);
                                    $res3 = deleteData('multi_lang',['mkey'=>$data['table'].'_value_'.$v1['id']]);
                                }
                                ltrim($content,',');
                                if($res3){
                                    Db::commit();
                                    return json_encode(array('status'=>1,'msg'=>lang('product_properties')."->".$content.' '.lang('cleared_successfully')));
                                }else{
                                    return json_encode(array('status'=>0,'msg'=>lang('product_properties')."->".$content.' '.lang('clear_failed')));
                                }
                            }else{
                                return json_encode(array('status'=>0,'msg'=>lang('clear_failed')));
                            }
                            
                        }
                    }else{
                        $proattrRes = getDatas('proattr',['*'],['id'=>$data['id']]);
                        if(!empty($proattrRes)){
                            if($proattrRes[0]['status'] !=2){
                                return json_encode(array('status'=>2,'msg'=>lang("the_current_attribute_can't_be_cleared,_and_the_status_isn't_recycled")));
                            }

                            if($proattrRes[0]['is_public'] ==1){
                                return json_encode(array('status'=>2,'msg'=>lang('clear_failed').' '.lang('attributes_common,_need_to_disarm_first')));
                            }
                        }
                        // 获取旗下所有属性值ID
                        $delIds = getDatas('proattr_value',['id'],['proattr_id'=>$data['id']]);
                        // 删除旗下所有属性值
                        $res = deleteData('proattr',['id'=>$data['id']]); 
                        if($res){
                            $res2 = deleteData('proattr_value',['proattr_id'=>$data['id']]); 
                            if(count($delIds) > 0){
                                foreach ($delIds as $k => $v) {
                                    if($k < 4){
                                        $content .= ','.getValue('multi_lang',['mkey'=>'proattr_'.$v['id']],'content');
                                    }
                                    if($k = 4){
                                        $content .= '';
                                    }
                                    $res1 = deleteData('multi_lang',['mkey'=>$data['table'].'_'.$data['id']]);
                                    $res3 = deleteData('multi_lang',['mkey'=>$data['table'].'_value_'.$v['id']]);
                                }
                            }
                            ltrim($content,',');
                            if($res2 && $res3 ){
                                // Db::commit();
                                return json_encode(array('status'=>1,'msg'=>lang('product_properties')."->".$content.' '.lang('cleared_successfully')));
                            }else{
                                return json_encode(array('status'=>0,'msg'=>lang('product_properties')."->".$content.' '.lang('clear_failed')));
                            }
                        }else{
                            return json_encode(array('status'=>0,'msg'=>lang('product_properties')."->".$content.' '.lang('clear_failed')));
                        }
                    }

                // }catch(\Exception $e){
                //     Db::rollback();
                //     return json_encode(array('status'=>500,'msg'=>$e);
                // }
            }
        }else{
            return json_encode(array('status' => 3,'msg'=>'请勾选需要操作的产品属性'));
        }

    }

    // 批量/单个删除
    public function batchDel()
    {
        return $this->changeStatus($this->data,$this->lang);
    }

    // 批量/单个下架
    public function batchObtained()
    {
        return $this->changeStatus($this->data,$this->lang);
    }

    // 批量/单个恢复
    public function batchRestore()
    {
        return $this->changeStatus($this->data,$this->lang);
    }

    // 批量/单个清除
    public function batchClear()
    {
        return $this->changeStatus($this->data,$this->lang);
    }

    // 批量/单个隐藏
    public function batchHide()
    {
        return $this->changeStatus($this->data,$this->lang);
    }
}
